$(function () {

    adjustContentHeight();

    movePointerTo($('.navbar-main li.active'));

    $(window).resize(function () {
        adjustContentHeight();
        if (!$('.pointer').hasClass('aligned')) {
            movePointerTo($('.navbar-main li.active'));
        }
    });
});
// use js cache
$.ajaxSetup({
    cache: true
});

// global config
var DEBUG = true;

// global object
var TIMER = {},
    HOST = "aota-admin/";
//    HOST = '';

function log(message) {
    if (DEBUG) {
        if (window.console) {
            window.console.log(message);
        }
    }
}

function lozLogin() {
    window.location = HOST + '/admin/login'
}

function alertModal(txt) {
    var jqAlertMadal = $("#alertModal");
    jqAlertMadal.find(".modal-body").text(txt);
    jqAlertMadal.modal("show");
}

function confirmModal(txt, success) {
    var jqConfirmMadal = $("#confirmModal");
    jqConfirmMadal.find(".modal-body").text(txt);
    jqConfirmMadal.modal("show");

    jqConfirmMadal.find(".btn-ok").off().on("click", function () {
        success();
    });
}

function loadStyle(url) {
    if ($('link[href="' + url + '"]').length) {
        return;
    } else {
        if (document.createStyleSheet) {
            document.createStyleSheet(url);
        } else {
            $('<link rel="stylesheet" href="' + url + '" />').appendTo('head');
        }
    }
}

function loadScript(url) {
    $('<script src="' + url + '" /></script>').appendTo('.route-view');
}

function isChrome() {
    return window.navigator.userAgent.indexOf("Chrome") !== -1;
}

function movePointerTo(elem) {
    if ($(window).width() > 975) {
        $('.pointer')
            .removeClass('aligned')
            .css({
                'top': 'auto',
                'bottom': 0,
                'left': elem.offset().left + 'px',
                'width': elem.width(),
                'height': 4
            })
            .addClass('aligned');
    }
}

function activeElem(elem) {

    elem.addClass('active');
}

function adjustContentHeight() {
    var avaliableHeight = $(window).height() - 168;
    $('#main-content-body').css('height', avaliableHeight);
}

function resizeTable(extra) {
    var avaliableHeight = $('#main-content-body').height() - $('.form-inline').height() - $('.table-result thead').height() - extra;
    var scrollbarWidth = getScrollbarWidth();
    $('.result').css('padding-right', scrollbarWidth);
    $('.tbody').css({
        'overflow-y': 'scroll',
        'height': avaliableHeight,
        'margin-right': -scrollbarWidth
    });
}

function obj2Array(obj) {
    var arr = [],
        i = 0;
    while (obj[i] !== undefined) {
        arr = arr.concat(obj[i]);
        i++;
    }
    return arr;
}

function getArrSum(arr) {
    var sum = 0;
    for (var i = 0; i < arr.length; i++) {
        if (typeof +arr[i] !== 'number') continue;
        sum += arr[i];
    }
    return sum;
}

function convertChartData(arr, type) {
    var dayLabel = ["", "3", "6", "9", "12", "15", "18", "21", "24", "(hours)"],
        weekLabel = ["", "1", "2", "3", "4", "5", "6", "7", "(day)"],
        monthLabel = ["", "1", "2", "3", "4", "(week)"],
        quarterlyLabel = ["", "1", "2", "3", "(month)"];

    var chartData = arr;

    //set first null
    function setFirstNUll(data) {
        data = [].concat.apply([null], data);
        return data;
    }

    chartData.download = setFirstNUll(chartData.download);
    chartData.install = setFirstNUll(chartData.install);
    chartData.upgrade = setFirstNUll(chartData.upgrade);

    var labels = null;
    var options = {
        animation: true,
        scaleFontSize: 10,
        tooltipFontSize: 12,
        tooltipCornerRadius: 2,
        scaleLineColor: "rgba(0,0,0,.06)",
        scaleShowGridLines: false,
        bezierCurve: false,
        pointDotStrokeWidth: 2,
        gradientFill: true
    };
    // only chrome use animation
    // if(isChrome()) {
    //     $.extend(options, {
    //         animation: true
    //     });
    // }

    if (type === "hours") {
        labels = dayLabel;

    } else if (type === "days") {
        labels = weekLabel;

    } else if (type === "weeks") {
        labels = monthLabel;

    } else if (type === "months") {
        labels = quarterlyLabel;
    }

    return {
        data: {
            labels: labels,
            datasets: [
                {
                    label: "chart",
                    fillColor: ["rgba(0, 156, 222, 0.15)", "rgba(0, 156, 222, 0.09)", "rgba(0, 156, 222, 0)"],
                    strokeColor: "#009cde",
                    pointColor: "#009cde",
                    pointStrokeColor: "#009cde",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(0, 156, 222,0.5)",
                    data: chartData.download
                },
                {
                    label: "chart",
                    fillColor: ["rgba(180, 142, 173, 0.15)", "rgba(180, 142, 173, 0.09)", "rgba(180, 142, 173, 0)"],
                    strokeColor: '#b48ead',
                    pointColor: "#b48ead",
                    pointStrokeColor: '#b48ead',
                    pointHighlightFill: '#fff',
                    pointHighlightStroke: 'rgba(163, 190, 140,0.5)',
                    data: chartData.install
                },
                {
                    label: "chart",
                    fillColor: ["rgba(163, 190, 140, 0.24)", "rgba(163, 190, 140, 0.15)", "rgba(163, 190, 140, 0)"],
                    strokeColor: '#a3be8c',
                    pointColor: "#a3be8c",
                    pointStrokeColor: '#a3be8c',
                    pointHighlightFill: '#fff',
                    pointHighlightStroke: 'rgba(163, 190, 140,0.5)',
                    data: chartData.upgrade
                }
            ]
        },
        options: options
    };
}

function getScrollbarWidth() {
    var outer = document.createElement("div");
    outer.style.visibility = "hidden";
    outer.style.width = "100px";
    outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

    document.body.appendChild(outer);

    var widthNoScroll = outer.offsetWidth;
    // force scrollbars
    outer.style.overflow = "scroll";

    // add innerdiv
    var inner = document.createElement("div");
    inner.style.width = "100%";
    outer.appendChild(inner);

    var widthWithScroll = inner.offsetWidth;

    // remove divs
    outer.parentNode.removeChild(outer);
    return widthNoScroll - widthWithScroll;
}

//table checked item id form check
function getTableCheckedId($table) {
    $table = $table || $(".table-result");
    var arr = [];
    $table.find(".chk-item.checked[data-id]").each(function () {
//        arr.push(+$(this).attr("data-id"));
        arr.push($(this).data("id"));
    });
    return arr;
}

function getSuffix(str) {
    var strArr = str.split('.');
    return strArr[strArr.length - 1];
}

function isImage(str) {
    return getSuffix(str) === 'jpg' || getSuffix(str) === 'png' || getSuffix(str) === 'gif';
}

function uploadFile(uploadParams) {
    var modal = uploadParams.modal,
        file = uploadParams.file,
        useFormData = uploadParams.useFormData,
        fileName = uploadParams.fileName,
        url = uploadParams.url,
        onProgress = uploadParams.onProgress,
        onSuccess = uploadParams.onSuccess,
        onFailure = uploadParams.onFailure,
        onComplete = uploadParams.onComplete;

    var xhr = new XMLHttpRequest();
    if (xhr.upload) {
        // 上传中
        xhr.upload.addEventListener("progress", function (e) {
            onProgress(file, e.loaded, e.total);
        }, false);

    }
    var data = null;
    if (useFormData) {
        data = new FormData();
        data.append(fileName, file);
    } else data = file;

    // 文件上传成功或是失败
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                onSuccess(file, xhr.responseText);
            } else {
                onFailure(file, xhr.responseText);
            }
            onComplete();
        }
        if(xhr.readyState >= 1 && xhr.readyState < 4){
            if(modal){
                modal.off("hidden.bs.modal").on("hidden.bs.modal", function(){
                    xhr.abort();
                });
            }
        }
    };

    // 开始上传
    xhr.open("POST", url, true);
    xhr.setRequestHeader("X_FILENAME", unescape(encodeURIComponent(file.name)));
    xhr.send(data);
}

function imageReader(file, callback) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        if (typeof callback === 'function') callback(e.target.result);
    };
}

/**
 * pagination
 * @param id, container
 * @param pIndex, current page num
 * @param pCount, total page num
 * @param pTotal, total data num
 * @param isLast
 * @param callback
 */
function pagination(id, currentPageNum, totalPageNum, totalDataNum) {
    //create page
    function creatPage(i) {
        return $('<a class="goto" data-page="' + i + '">' + i + '</a>');
    }

    var $box = $(id);
    $box.html('');

    // total page
    $box.append('<a class="">Total' + totalDataNum + ' / ' + totalPageNum + 'pages</a>');

    // index page
    var $firstPage = $('<a class="page goto" data-page="1">First</a>');

    // prev page
    var $prevPage = $('<a class="prev goto" data-page="' + (currentPageNum - 1) + '">Prev</a>');

    if (currentPageNum > 1) {
        $box.append($firstPage).append($prevPage);
    }
    // prev current page
    for (var i = currentPageNum - 5; i < currentPageNum; i++) {
        if (i > 0) {
            $box.append(creatPage(i));
        }
    }
    // current page
    $box.append('<a class="on">' + currentPageNum + '</a>');

    // next current page
    for (var j = currentPageNum + 1; j <= currentPageNum + 5; j++) {
        if (j <= totalPageNum) {
            $box.append(creatPage(j));
        }
    }
    // next page
    var $nextPage = $('<a class="next goto" data-page="' + (currentPageNum + 1) + '">Next</a>');

    // last page
    var $lastPage = $('<a class="page goto" data-page="' + totalPageNum + '">Last</a>');

    if (currentPageNum < totalPageNum) {
        $box.append($nextPage).append($lastPage);
    }

    // input turn page
    var $jumpPage = $('<a class="page-ipt-wrap">' +
        '<input type="text" class="form-control" value="' + i + '"></a>' +
        '<a  href="javascript:void(0);" id="go">Confirm</a>');
    $box.append($jumpPage);
}
/**
 *
 * @param $pagination
 * @param totalPage
 */
function jumpToPage($pagination, totalPage, callback) {
    var tempVal,
        $ipt = $("input", $pagination),
        $go = $("#go", $pagination);

    // get old value
    $ipt.focus(function () {
        tempVal = $.trim($(this).attr('placeholder'));
    });

    //click btn
    $go.on('click', function () {
        var nowVal = $.trim($ipt.val());
        if (isNaN(nowVal)) {
            alertModal('Please enter a valid number');
            $ipt.val(tempVal);
            return false;
        } else if (nowVal > totalPage || nowVal == 0) {
            alertModal('Sorry, pages between 1~' + totalPage);
            $ipt.val(tempVal);
            return false;
        }
        if (nowVal != tempVal) {
            if (callback) callback(nowVal);
        }
    });

    //key down input
    $ipt.on('keydown', function (event) {
        var e = event || window.event;
        if (e && e.keyCode == 13) {
            event.preventDefault();
            $pagination.find('#go').trigger('click');
            return false;
        }
    });
}